//
//  ViewController.swift
//  Ofo-demo
//
//  Created by 张彦辉 on 2017/5/16.
//  Copyright © 2017年 张彦辉. All rights reserved.
//

import UIKit
import FTIndicator

class ViewController: UIViewController {

    @IBOutlet weak var panelView: UIView!
    @IBAction func locationClick(_ sender: UIButton) {
        searchCustomLocation(mapView.userLocation.coordinate,true)
    }
    
    var mapView:MAMapView!
    var search:AMapSearchAPI!
    var pin:MyPinAnnotation!
    var pinView:MAPinAnnotationView!
    var nearBySearch:Bool!
    var walkManager:AMapNaviWalkManager!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mapView = MAMapView(frame: self.view.bounds)
        self.view.addSubview(mapView)
        self.view.bringSubview(toFront: panelView)
        
        mapView.delegate = self
        
        mapView.zoomLevel = 17
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow
        
        search = AMapSearchAPI()
        search.delegate = self
        
        walkManager = AMapNaviWalkManager()
        walkManager.delegate = self
        
        self.navigationItem.titleView = UIImageView(image: #imageLiteral(resourceName: "ofoLogo"))
        self.navigationItem.leftBarButtonItem?.image = #imageLiteral(resourceName: "leftTopImage").withRenderingMode(.alwaysOriginal)
        self.navigationItem.rightBarButtonItem?.image = #imageLiteral(resourceName: "rightTopImage").withRenderingMode(.alwaysOriginal)
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    

}
// MARK: -- 地图显示代理
extension ViewController: MAMapViewDelegate{
    // MARK: -- 地图上显示图片回调
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        if annotation is MAUserLocation {
            return nil
        }else if annotation is MyPinAnnotation {
            let indexId = "annotationId1"
            var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: indexId) as? MAPinAnnotationView
            if pinView == nil {
                pinView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: indexId)
            }
            pinView?.canShowCallout = false
            
            pinView?.image = #imageLiteral(resourceName: "homePage_wholeAnchor")
            self.pinView = pinView
            return pinView
        }else{
            let indexId = "annotationId2"
            var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: indexId) as? MAPinAnnotationView
            if pinView == nil {
                pinView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: indexId)
            }
            pinView?.canShowCallout = true
            pinView?.animatesDrop = false
            pinView?.isDraggable = true
            pinView?.image = #imageLiteral(resourceName: "HomePage_nearbyBike")
            return pinView
        }
    }
    
    // MARK: --地图初始化完成，增加中心点
    func mapInitComplete(_ mapView: MAMapView!) {
        pin = MyPinAnnotation()
        pin.coordinate = mapView.centerCoordinate
        pin.lockedScreenPoint = CGPoint(x: view.bounds.width/2, y: view.bounds.height/2)
        pin.isLockedToScreen = true
        mapView.addAnnotation(pin)
        mapView.showAnnotations([pin], animated: true)
    }
    //MARK: -- 用户移动地图结束跟据中心点重新加载周边小黄车
    func mapView(_ mapView: MAMapView!, mapDidMoveByUser wasUserAction: Bool) {
        if wasUserAction {
            pin.isLockedToScreen = true
            pinAnimate()
            searchCustomLocation(mapView.centerCoordinate,false)
            
        }
    }
    
    // MARK: -- 添加小黄车动画
    func mapView(_ mapView: MAMapView!, didAddAnnotationViews views: [Any]!) {
        let aViews = views as! [MAAnnotationView]
        for aView in aViews {
            guard aView.annotation is MAPointAnnotation else {
                continue
            }
            aView.transform = CGAffineTransform(scaleX: 0, y: 0)
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0, options: [], animations: { 
                aView.transform = .identity
            }, completion: nil)
        }
    }
    // MARK: -- 选中一个小黄车
    func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) {
//        let startPoint = AMapNaviPoint.location(withLatitude: 39.993135, longitude: 116.474175)!
//        let endPoint = AMapNaviPoint.location(withLatitude: 39.908791, longitude: 116.321257)!
        let userLocation = mapView.userLocation.coordinate
        let endLocation = view.annotation.coordinate
        
        let startPoint = AMapNaviPoint.location(withLatitude: CGFloat(userLocation.latitude), longitude: CGFloat(userLocation.longitude))!
        let endPoint = AMapNaviPoint.location(withLatitude: CGFloat(endLocation.latitude), longitude: CGFloat(endLocation.longitude))!
        
        walkManager.calculateWalkRoute(withStart: [startPoint], end: [endPoint])
        
    }
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        if overlay is MAPolyline {
            pin.isLockedToScreen = false
            mapView.visibleMapRect = overlay.boundingMapRect
            
            let renderer: MAPolylineRenderer = MAPolylineRenderer(overlay: overlay)
            renderer.lineWidth = 8.0
            renderer.strokeColor = UIColor.cyan
            
            return renderer
        }
        return nil
    }
}

// MARK: -- 地图搜索代理
extension ViewController: AMapSearchDelegate{
    // MARK: -- 查询结果回调
    func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
        guard response.count > 0 else {
            print("周边没有小黄车")
            return
        }
        let pointAnnotation : [MAPointAnnotation] = response.pois.map {
            let annotation = MAPointAnnotation()
            annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees($0.location.latitude), longitude: CLLocationDegrees($0.location.longitude))
            annotation.title = "ofo共享单车"
            annotation.subtitle = "subtitle"
            return annotation
        }
        mapView.addAnnotations(pointAnnotation)
        if nearBySearch {
            mapView.showAnnotations(pointAnnotation, animated: true)
        }
        
    }
}

// MARK: -- 工具扩展
extension ViewController{
    // MARK: -- 查询指定坐标周边数据
    func searchCustomLocation(_ center: CLLocationCoordinate2D,_ nearBySearch:Bool) {
        self.nearBySearch = nearBySearch
        
        let request = AMapPOIAroundSearchRequest()
        request.location = AMapGeoPoint.location(withLatitude: CGFloat(center.latitude), longitude: CGFloat(center.longitude))
        request.keywords = "餐馆"
        request.radius = 500
        request.requireExtension = true
        search.aMapPOIAroundSearch(request)
    }
    // MARK: -- 大头针动画
    func pinAnimate() {
        let endFrame = pinView.frame
        pinView.frame = endFrame.offsetBy(dx: 0, dy: -15)
        UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0, options: [], animations: { 
            self.pinView.frame = endFrame
        }, completion: nil)
    }
    
}

extension ViewController: AMapNaviWalkManagerDelegate{
    // MARK: -- 步行线路规划
    func walkManager(onCalculateRouteSuccess walkManager: AMapNaviWalkManager) {
        mapView.removeOverlays(mapView.overlays)
        var lineCoordinates = walkManager.naviRoute!.routeCoordinates!.map({ (p) -> CLLocationCoordinate2D in
            return CLLocationCoordinate2D(latitude: CLLocationDegrees(p.latitude), longitude: CLLocationDegrees(p.longitude))
        })
        
        let polyline = MAPolyline(coordinates: &lineCoordinates, count: UInt(lineCoordinates.count))
        mapView.add(polyline)
    
        //提示时间和距离
        let walkMinute = (walkManager.naviRoute!.routeTime) / 60
        let walkLength = walkManager.naviRoute!.routeLength
        var timeDesc = "1分钟以内"
        if walkMinute > 0 {
            timeDesc = "\(walkMinute)分钟"
        }
        let hintTime = "步行" + timeDesc
        let hintSubtitle = "距离\(walkLength)米"
        
        FTIndicator.setIndicatorStyle(.dark)
        FTIndicator.showNotification(with: #imageLiteral(resourceName: "clock"), title: hintTime, message: hintSubtitle)
        
    }
}

